<?php
namespace Admin\Logic;

use Admin\Common\Category;
use Think\Log;
class CateLogic
{

    /**
     * 获取分类列表
     * @return bool
     */
    public static function getAll($where = false)
    {
        try {
            $cate = D('Cate');
            if ($where == true) {
                $cate->where(['is_show' => true]);
            }
            $data = $cate->order('order_sort asc')->select();
            return $data;
        } catch (\Exception $e) {
            return false;
        }
    }

    public static function getShowCate()
    {
        try {
            $cate = D('Cate');
            $data = $cate->where(['is_show'=>1])->order('order_sort asc')->select();
            return $data;
        } catch (\Exception $e) {
            return false;
        }

    }



    /**
     * 执行添加分类操作
     * @param $param
     * @return array|bool
     */
    public static function create($param)
    {
        try {
            $cate = D('Cate');
            if (!$cate->create($param)) { //创建数据对象
                return ['code' => 1, 'msg' => $cate->getError()];
            } else {
                $id = $cate->add();
                return ['code' => 0, 'msg' => $id];
            }
        } catch (\Exception $e) {
            return false;
        }
    }


    /**
     * 修改分类操作
     * @param $data
     * @return bool
     */
    public static function update($data)
    {
        try {
            $update = D('Cate')->save($data);
            return $update;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 执行删除分类操作
     * @param $id
     * @return string
     */
    public static function delete($id)
    {
        // 判断是否有子分类
        $children = Category::isHaveChildren($id);
        if($children){
            // 存在子分类
            return json_encode(['code'=>0,'errorMsg'=>'请先删除其子分类']);
        }

        // 判断此分类下面是否有商品
        $goods = Category::isHaveGoods($id);

        if($goods == false){
            return json_encode(['code'=>0,'errorMsg'=>'服务器找不到了']);
        } elseif ($goods['code'] == 1){
            // 存在商品
            return json_encode(['code'=>0,'errorMsg'=>'请先删除分类下的商品']);
        }

        try {
            $update = D('Cate')->where('id='.$id)->delete();

            return json_encode(['code'=>1]);
        } catch (\Exception $e) {
            return json_encode(['code'=>0,'errorMsg'=>'删除失败，请重试']);
        }
    }

    public static function getCateStock()
    {

    }



}